const Verif = {
  createVerifCode: function (id, txt, w, h) {
    let canvas = document.getElementById(id);
    let txtInput = document.getElementById(txt);
    let ctx;
    canvas.width = w;
    canvas.height = h;
    if (canvas !== null && canvas.getContext) {
      ctx = canvas.getContext('2d');
    } else {
      return;
    }
    ctx.textBaseline = "middle";
    ctx.fillStyle = randomColor(180, 240);

    ctx.fillRect(0, 0, w, h);

    let numArr = "0,1,2,3,4,5,6,7,8,9".split(",");
    let txtArr = numArr.concat(getAllLetter());
    let returnTxt = '';
    for (let i = 1; i <= 4; i++) {
      let txt = txtArr[randomNum(0, txtArr.length)];
      returnTxt += txt;
      ctx.font = randomNum(h / 2, h) + 'px SimHei'; //随机生成字体大小
      ctx.fillStyle = randomColor(50, 160); //随机生成字体颜色
      ctx.shadowOffsetX = randomNum(-3, 3);
      ctx.shadowOffsetY = randomNum(-3, 3);
      ctx.shadowBlur = randomNum(-3, 3);
      ctx.shadowColor = "rgba(0, 0, 0, 0.3)";
      let x = w / 5 * i;
      let y = h / 2;
      let deg = randomNum(-30, 30);
      /**设置旋转角度和坐标原点**/
      ctx.translate(x, y);
      ctx.rotate(deg * Math.PI / 180);
      ctx.fillText(txt, 0, 0);
      /**恢复旋转角度和坐标原点**/
      ctx.rotate(-deg * Math.PI / 180);
      ctx.translate(-x, -y);
    }
    /**绘制干扰线**/
    for (let i = 0; i < 4; i++) {
      ctx.strokeStyle = randomColor(40, 180);
      ctx.beginPath();
      ctx.moveTo(randomNum(0, w), randomNum(0, h));
      ctx.lineTo(randomNum(0, w), randomNum(0, h));
      ctx.stroke();
    }
    /**绘制干扰点**/
    for (let i = 0; i < w / 4; i++) {
      ctx.fillStyle = randomColor(0, 255);
      ctx.beginPath();
      ctx.arc(randomNum(0, w), randomNum(0, h), 1, 0, 2 * Math.PI);
      ctx.fill();
    }
    txtInput.value = returnTxt;
  }
};

/**生成字母数组**/
function getAllLetter() {
  let letterStr = "a,b,c,d,e,f,g,h,i,j,k,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,S,T,U,V,W,X,Y,Z";
  return letterStr.split(",");
}

/**生成一个随机数**/
function randomNum(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

/**生成一个随机色**/
function randomColor(min, max) {
  let r = randomNum(min, max);
  let g = randomNum(min, max);
  let b = randomNum(min, max);
  return "rgb(" + r + "," + g + "," + b + ")";
}

export default Verif;
